#include "Config.h"
#include "Common/Stream.h"
#include "Common/Itoa.h"
#include "Common/TimeUtil.h"
#include "GameReport.h"
#include "GameSimulator.h"
#include "Server/IDGenerator.h"
#include "../Player.h"
#include "../PlayerManager.h"
#include "DB/DBExecutor.h"
#include "../Server.h"
#include "wch/DirectoryIterator.h"
using namespace wch;

GameReport::GameReport()
{

}

GameReport::~GameReport()
{
	
}

std::vector<UInt32> GameReport::getReportIds()
{
	std::vector<UInt32> ids;
	Player * pl = _gs->getOneGamePlayer();
	return pl->getGameReportIds();
}

bool GameReport::prepare( GameSimulator * gs )
{
	_gs = gs;
	_rid = gs->getRoom()->getId();
	_time = TimeUtil::Now();
	return true;
}

bool GameReport::add( UInt64 pid, Stream& st )
{
	GamePacket gp = GamePacket(pid, st);
	if (gp._cmd < 0x1A || gp._cmd > 0x1D)
		return false;
	_packets.push_back( gp );
	return true;
}

void GameReport::end()
{
	Stream st( 0x31 );
	st << static_cast<UInt8>(0);
	st << _rid << _time;
	std::vector<GamePlayerData>& gpds = _gs->getRoom()->getGamePlayerDatas();
	//append player data
	{
		st << static_cast<UInt16>(gpds.size());
		for (size_t i = 0; i < gpds.size(); ++i)
		{
			st << gpds[i]._uid << gpds[i]._nick << gpds[i]._sex << gpds[i]._headIcon << gpds[i]._pos;
			UInt32 score = 0;
			if (gpds[i]._score < 0)
			{
				st << static_cast<UInt8>(0);
				score = -gpds[i]._score;
			}
			else
			{
				st << static_cast<UInt8>(1);
				score = gpds[i]._score;
			}
			st << score;
		}
	}
	st << static_cast<UInt16>(_packets.size());
	for ( auto itr = _packets.begin(); itr != _packets.end(); ++ itr )
	{
		GamePacket& packet = *itr;
		st << packet._pid << packet._time << packet._cmd << packet._len;
		st.append( &packet._buffer[0], packet._buffer.size() );
	}
	st << Stream::eos;
	//send to hall
	{
		Stream st2(0x20A);
		st2 << static_cast<UInt32>(0) << _rid << _time;
		for (UInt8 i = 0; i < gpds.size(); ++i)
		{
			st2 << gpds[i]._uid << gpds[i]._nick;
			if (gpds[i]._score >= 0)
			{
				st2 << static_cast<UInt8>(0);
				st2 << static_cast<Int32>(gpds[i]._score);
			}
			else
			{
				st2 << static_cast<UInt8>(1);
				st2 << static_cast<Int32>(-gpds[i]._score);
			}
		}
		//
		st2 << static_cast<UInt16>(st.size());
		st2.append(&st[0], st.size());
		st2 << Stream::eos;
		NETWORK()->SendToHall( st2 );
	}
}